<template>
  <div class="ele-body">
    <a-card :bordered="false" title="入库单主表">
      <a-form ref="entryBillFormRef" :model="entryBillForm" :rules="entryBillRules"
        :label-col="{ md: { span: 4 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 20 }, sm: { span: 24 } }">
        <a-row :gutter="16">
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="入库单号" name="code">
              {{ entryBillForm.code }}
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="供应商" name="supplier_val">
              <a-auto-complete v-model:value="entryBillForm.supplier_val" :options="supplierOptions"
                placeholder="请输入供应商" @select="supplier_onSelect" @search="supplier_onSearch" @blur="supplier_blur"
                allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="入库日期" name="entrytime">
              <a-date-picker v-model:value="entryBillForm.entrytime" valueFormat="YYYY-MM-DD HH:mm:ss"
                :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }" placeholder="请输入入库日期" class="ele-fluid"
                allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="付款" name="state">
              <a-select v-model:value="entryBillForm.state" placeholder="请选择">
                <a-select-option value="已付款">已付款</a-select-option>
                <a-select-option value="未付款">未付款</a-select-option>
                <a-select-option value="部分付款">部分付款</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="未付款金额" name="unpaid">
              <!-- <a-input-number allow-clear :maxlength="200" placeholder="请输入未付款金额" v-model:value="entryBillForm.unpaid"
                class="ele-fluid" autocomplete="off" /> -->
              <a-input allow-clear :maxlength="200" placeholder="请输入未付款金额" v-model:value="entryBillForm.unpaid"
                class="ele-fluid" autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="总金额" name="total">
              {{ entryBillForm.total }}
              <!-- <a-input-number :maxlength="200" placeholder="请输入总金额" v-model:value="entryBillForm.total" class="ele-fluid"
                autocomplete="off" /> -->
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="开票" name="invoice">
              <a-select v-model:value="entryBillForm.invoice" placeholder="请选择">
                <a-select-option value="已开票">已开票</a-select-option>
                <a-select-option value="未开票">未开票</a-select-option>
                <a-select-option value="无">无</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24" :xs="24">
            <a-form-item label="备注" name="remark" :label-col="{ md: { span: 2 }, sm: { span: 24 } }"
              :wrapper-col="{ md: { span: 22 }, sm: { span: 24 } }">
              <a-textarea :rows="4" :maxlength="200" placeholder="请输入备注" v-model:value="entryBillForm.remark"
                autocomplete="off" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :md="24" :sm="24" :xs="24" class="right">
            <a-button type="dashed" @click="finishPageTab">关闭页面</a-button>
            <a-button type="primary" @click.prevent="entryBillSave" class="m5">保存</a-button>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <br />
    <a-card :bordered="false" title="入库单子表">
      <ele-pro-table ref="entryBillSonTableRef" row-key="id" :columns="columns" :datasource="datasource"
        :scroll="{ x: 1000 }" cacheKey="entryBillSon">
        <template #toolbar>
          <a-space>
            <a-button type="primary" @click="entryBillSonOpenEdit()" v-any-permission="['store:entryBillSon:save']">
              <template #icon>
                <plus-outlined />
              </template>
              <span>添加</span>
            </a-button>
          </a-space>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="entryBillSonOpenEdit(record)" v-any-permission="['store:entryBillSon:update']">修改</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定要删除此项吗？" @confirm="entryBillSonRemove(record)">
                <a class="ele-text-danger" v-any-permission="['store:entryBillSon:remove']">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- 入库单子表添加、修改弹窗 -->
    <ele-modal :width="860" v-model:visible="entryBillSonVisible_modal" :confirm-loading="loading"
      :title="entryBillSonIsUpdate ? '修改入库单子表' : '添加入库单子表'" position="center" :body-style="{ paddingBottom: '8px' }"
      @ok="entryBillSonSave" :maskClosable="false">
      <a-form ref="entryBillSonFormRef" :model="entryBillSonForm" :rules="entryBillSonRules"
        :label-col="{ md: { span: 7 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
        <a-row :gutter="16">
          <a-col :md="8" :sm="24" :xs="24" v-if="!entryBillSonForm.id">
            <a-form-item label="产品选择" name="">
              <a-button danger @click="openProduct">选择</a-button>
            </a-form-item>
          </a-col>
          <a-col :md="16" :sm="24" :xs="24" v-if="!entryBillSonForm.id">
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="仓库" name="warehousename_val" class="storage">
              <template v-if="entryBillSonIsUpdate">
                {{ entryBillSonForm.warehousename_val }}
              </template>
              <a-auto-complete v-else v-model:value="entryBillSonForm.warehousename_val" :options="warehousenameOptions"
                placeholder="请输入仓库" @select="warehousename_onSelect" @search="warehousename_onSearch"
                @blur="warehousename_blur" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="库存数量" name="num2">
              {{ entryBillSonForm.num2 }}
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="库存重量" name="litotalweight2">
              {{ entryBillSonForm.litotalweight2 }}
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="产品" name="productname_val" class="storage">
              <template v-if="entryBillSonIsUpdate">
                {{ entryBillSonForm.productname_val }}
              </template>
              <a-auto-complete v-else v-model:value="entryBillSonForm.productname_val" :options="productnameOptions"
                placeholder="请输入产品" @select="productname_onSelect" @search="productname_onSearch"
                @blur="productname_blur" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="规格" name="specification" class="storage">
              {{ entryBillSonForm.specification }}
              <!-- <template v-if="entryBillSonIsUpdate">
                {{ entryBillSonForm.specification }}
              </template>
              <a-input v-else allow-clear :maxlength="200" placeholder="请输入规格"
                v-model:value="entryBillSonForm.specification" @blur="countBlur" autocomplete="off" /> -->
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="长度" name="lengths" class="storage">
              <template v-if="entryBillSonIsUpdate">
                {{ entryBillSonForm.lengths }}
              </template>
              <!-- <a-input-number v-else allow-clear :maxlength="200" placeholder="请输入长度"
                v-model:value="entryBillSonForm.lengths" @blur="countBlur" class="ele-fluid" autocomplete="off" /> -->
              <a-input allow-clear v-else :maxlength="200" placeholder="请输入长度" v-model:value="entryBillSonForm.lengths"
                @blur="countBlur" autocomplete="off" class="ele-fluid" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="负差" name="negative" class="storage">
              <template v-if="entryBillSonIsUpdate">
                {{ entryBillSonForm.negative }}
              </template>
              <!-- <a-input-number v-else :maxlength="200" placeholder="请输入负差" v-model:value="entryBillSonForm.negative"
                @blur="countBlur" class="ele-fluid" autocomplete="off" /> -->
              <a-input allow-clear v-else :maxlength="200" placeholder="请输入负差" v-model:value="entryBillSonForm.negative"
                @blur="countBlur" class="ele-fluid" autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="理论质量" name="liweight">
              <template v-if="entryBillSonIsUpdate">
                {{ entryBillSonForm.liweight }}
              </template>
              <!-- <a-input-number v-else :maxlength="200" placeholder="请输入理论质量" v-model:value="entryBillSonForm.liweight"
                @blur="countBlur" class="ele-fluid" autocomplete="off" /> -->
              <a-input allow-clear v-else :maxlength="200" placeholder="请输入理论质量"
                v-model:value="entryBillSonForm.liweight" @blur="countBlur" class="ele-fluid" autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="数量" name="num">
              <!-- <a-input-number :maxlength="200" placeholder="请输入数量" v-model:value="entryBillSonForm.num"
                @blur="countBlur" class="ele-fluid" autocomplete="off" /> -->
              <a-input allow-clear :maxlength="200" placeholder="请输入数量" v-model:value="entryBillSonForm.num"
                @blur="countBlur" class="ele-fluid" autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="总重量" name="litotalweight">
              <!-- <a-input-number :maxlength="200" placeholder="请输入总重量" v-model:value="entryBillSonForm.litotalweight"
                @blur="litotalweightBlur" class="ele-fluid" autocomplete="off" /> -->
              <a-input allow-clear :maxlength="200" placeholder="请输入总重量" v-model:value="entryBillSonForm.litotalweight"
                @blur="litotalweightBlur" class="ele-fluid" autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="销售重量" name="actualweight">
              <!-- <a-input-number :maxlength="200" placeholder="请输入销售重量" v-model:value="entryBillSonForm.actualweight"
                @blur="priceBlur" class="ele-fluid" autocomplete="off" /> -->
              <a-input allow-clear :maxlength="200" placeholder="请输入销售重量" v-model:value="entryBillSonForm.actualweight"
                @blur="priceBlur" class="ele-fluid" autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="价格" name="price">
              <!-- <a-input-number :maxlength="200" placeholder="请输入价格" v-model:value="entryBillSonForm.price"
                @blur="priceBlur" class="ele-fluid" autocomplete="off" /> -->
              <a-input allow-clear :maxlength="200" placeholder="请输入价格" v-model:value="entryBillSonForm.price"
                @blur="priceBlur" autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="总价" name="totalprice">
              <!-- <a-input-number :maxlength="200" placeholder="请输入总价" v-model:value="entryBillSonForm.totalprice"
                class="ele-fluid" autocomplete="off" /> -->
              <a-input allow-clear :maxlength="200" placeholder="请输入总价" v-model:value="entryBillSonForm.totalprice"
                class="ele-fluid" autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="材质" name="model">
              <a-input allow-clear :maxlength="200" placeholder="请输入材质" v-model:value="entryBillSonForm.model"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="产地" name="locality">
              <a-input allow-clear :maxlength="200" placeholder="请输入产地" v-model:value="entryBillSonForm.locality"
                autocomplete="off" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </ele-modal>

    <!-- 产品列表选择 -->
    <ele-modal :width="1160" v-model:visible="productVisible_modal" :confirm-loading="productloading" title="产品列表"
      position="center" :body-style="{ paddingBottom: '8px' }" @ok="productSelect" :maskClosable="false">
      <productComp ref="productRef" @pSelect_s="pSelect_m" />
    </ele-modal>
  </div>
</template>

<script setup>
import { ref, reactive, watch, unref } from 'vue';
import { toDateString } from 'ele-admin-pro';
import useFormData from '@/utils/use-form-data';
import { message } from 'ant-design-vue';
import { TIME_OUT } from '@/config/damon';
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'


import productComp from '@/views/store/product/components/product.vue';
import { reloadPageTab, finishPageTab, setRouteReload, getRouteTabKey, setPageTabTitle, removePageTab } from '@/utils/page-tab-util';
import { pageEntryBill, getEntryBill, removeEntryBill, addEntryBill, updateEntryBill } from '@/api/store/entryBill';
import { sequenceCode } from '@/api/damon/sequence'
import { listCustomerSel } from '@/api/store/customer'
import { pageEntryBillSon, removeEntryBillSon, calcTotalPrice, addEntryBillSon, updateEntryBillSon } from '@/api/store/entryBillSon';
import { listWarehouseSel } from '@/api/store/warehouse'
import { listProductSel } from '@/api/store/product'
import { productStorageNum } from '@/api/store/productStorage'


// import request from '@/utils/request';

// let databaseParams = reactive({
//   database: 'damon_store_test',
//   packages: 'store',
//   tableName: 'we_sell_son',
//   tableNameJavaEntity: 'sellSon',
//   source: 'D:/moban/vm/',
//   sourceJava: 'main/java/com/eleadmin/',
//   sourceHtml: 'main/resources/templates/',
//   openSource: 'D\:\\moban\\vm',
// })


// async function dataBaseFn(params) {
//   const res = await request.get('/damon/database/dataBase', { params });
//   if (res.data.code === 0 && res.data.data) {
//     return res.data.data;
//   }
//   return Promise.reject(new Error(res.data.message));
// }


// document.body.addEventListener('keyup', (e) => {
//   // console.log(database)
//   if (e.key == 'd') {
//     dataBaseFn(databaseParams).then((msg) => {
//       //  console.log(msg);
//       message.success('生成成功');
//     })
//   }
// })




const route = useRoute()
const router = useRouter()
const { currentRoute } = useRouter();
//-------------main ----------------

// 是否是修改
const entryBillIsUpdate = ref(false);

//
const entryBillFormRef = ref(null);

// 表单数据
const { form: entryBillForm, resetFields: entryBillResetFormFields } = useFormData({
  id: undefined,
  customer: '',
  vessel: '',
  entrytime: '',
});

// 表单验证规则
const entryBillRules = reactive({
  supplier_val: [{
    required: true, message: '请输入供应商',
  }],
  entrytime: [{
    required: true, message: '请输入入库日期',
  }],
  unpaid: [{
    required: true, message: '请输入未付款金额',
  }],
});


//防止重复刷新
//供应商下拉列表
let supplier_m_timeout = 0
const supplierOptions = ref([]);
const supplier_onSearch = searchText => {
  clearTimeout(supplier_m_timeout)
  supplier_m_timeout = setTimeout(() => {
    listCustomerSel({ 'name': searchText }).then(msg => {
      supplierOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
supplier_onSearch('')
const supplier_onSelect = (value2, option2) => {
  // let a = supplierOptions.value.find((item)=> {return item.value=value})
  entryBillForm.supplier_val = option2.label
  entryBillForm.supplier = option2.label
  entryBillForm.supplierId = option2.value
};
const supplier_m_change = (value2) => {
  // let a = supplierOptions.value.find((item)=> {return item.value=value2})
  // entryBillForm.supplier_val=a.label
  // entryBillForm.supplier=a.label
};
const supplier_blur = () => {
  entryBillForm.supplier_val = entryBillForm.supplier
};

/* 打开编辑弹窗 */
const entryBillOpenEdit = () => {
  entryBillResetFormFields();
  entryBillFormRef.value?.clearValidate();
  entryBillForm.id = route.query?.id ?? 0
  if (entryBillForm.id) {
    setPageTabTitle('入库单修改')
    getEntryBill(entryBillForm.id).then((data) => {
      Object.assign(entryBillForm, data ?? {});
      entryBillForm.supplier_val = data.supplier
    })
  } else {
    setPageTabTitle('入库单添加')
    entryBillForm.entrytime = dayjs().format('YYYY-MM-DD HH:mm:ss')
    entryBillForm.state = '未付款'
    entryBillForm.invoice = '未开票'
    entryBillForm.total = 0
    entryBillForm.unpaid = 0
    //单号
    sequenceCode({ code: 'entry' }).then((msg) => {
      entryBillForm.code = msg
    })
  }
  entryBillIsUpdate.value = !!entryBillForm?.id;
};
//打开相同的组件 进入页面不执行默认的方法
// openFirst()
// function openFirst() {
//   const { query, path, fullPath } = currentRoute.value;
//   if (sessionStorage.getItem(fullPath)) {
//     if (!entryBillForm.code) {
//       sessionStorage.removeItem(fullPath)
//       openFirst()
//     }
//     return false
//   } else {
//     sessionStorage.setItem(fullPath, 1)
//   }
//   entryBillOpenEdit()
// }
// watch(() => getRouteTabKey(), (val) => {
//   openFirst()
// },
//   { deep: true }
// )
//打开相同的组件 进入页面不执行默认的方法
entryBillOpenEdit()
// 监听路由变化
watch(currentRoute, (val) => {
  const { query, path, fullPath } = unref(val);
  const id = query.id;
  if (path == '/store/entryBill_main') {  // 再做一下路由地址判断
    if (sessionStorage.getItem('entry') == 'on') {
      sessionStorage.setItem('entry', 'off')
      entryBillOpenEdit()
      try {
        entryBillSonReload()
      } catch (e) {
      }
    }
  }
}, {
  immediate: true
});

/* 保存编辑 */
const entryBillSave = () => {
  if (!entryBillFormRef.value) {
    return;
  }
  entryBillFormRef.value.validate().then(() => {
    const saveOrUpdate = entryBillIsUpdate.value ? updateEntryBill : addEntryBill;
    saveOrUpdate(entryBillForm).then((data) => {
      message.success(data.message);
      entryBillIsUpdate.value = !entryBillIsUpdate.value
      //库存页面刷新库存
      setRouteReload({
        reloadHome: false,
        reloadPath: '/store/entryBill'
      });
      //刷新本页
      if (entryBillIsUpdate.value) {
        entryBillForm.id = data.data
        router.push({ path: '/store/entryBill_main', query: { id: entryBillForm.id } })
      }
      // reloadPageTab()
      setPageTabTitle('入库单修改')
    }).catch((e) => {
      message.error(e.message);
    });
  }).catch(() => {
  });
};


//-------------main ----------------



//-------------son ----------------




// 表格实例
const entryBillSonTableRef = ref(null);

// 表格列配置
const columns = ref([
  {
    key: 'index',
    width: 48,
    align: 'center',
    fixed: 'left',
    hideInSetting: true,
    customRender: ({ index }) => index + (entryBillSonTableRef.value?.tableIndex ?? 0)
  },
  {
    title: '仓库',
    dataIndex: 'warehousename',
    key: 'warehousename',
    sorter: true
  },
  {
    title: '产品',
    dataIndex: 'productname',
    key: 'productname',
    sorter: true
  },
  {
    title: '规格',
    dataIndex: 'specification',
    key: 'specification',
    sorter: true
  },
  {
    title: '长度',
    dataIndex: 'lengths',
    key: 'lengths',
    sorter: true
  },
  {
    title: '负差',
    dataIndex: 'negative',
    key: 'negative',
    sorter: true
  },
  {
    title: '数量',
    dataIndex: 'num',
    key: 'num',
    sorter: true
  },
  {
    title: '理论质量',
    dataIndex: 'liweight',
    key: 'liweight',
    sorter: true
  },
  {
    title: '总重量',
    dataIndex: 'litotalweight',
    key: 'litotalweight',
    sorter: true
  },
  {
    title: '销售重量',
    dataIndex: 'actualweight',
    key: 'actualweight',
    sorter: true
  },
  {
    title: '价格',
    dataIndex: 'price',
    key: 'price',
    sorter: true
  },
  {
    title: '总价',
    dataIndex: 'totalprice',
    key: 'totalprice',
    sorter: true
  },
  {
    title: '材质',
    dataIndex: 'model',
    key: 'model',
    // sorter: true
    hideInTable: true,
  },
  {
    title: '产地',
    dataIndex: 'locality',
    key: 'locality',
    // sorter: true
    hideInTable: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    hideInTable: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '创建人',
    dataIndex: 'createName',
    key: 'createName',
    hideInTable: true,
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    hideInTable: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '更新人',
    dataIndex: 'updateName',
    key: 'updateName',
    hideInTable: true,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    fixed: 'right',
    hideInSetting: true
  }
]);

// 表单数据
const { form: entryBillSonWhere, resetFields } = useFormData({
  username: '',
  sex: undefined
});

// 表格数据源
let data_temp = {}
const datasource = async ({ page, limit, where, orders }) => {
  orders.sort = orders.sort == 'updateTime' ? 'update_time' : orders.sort
  orders.sort = orders.sort == 'createTime' ? 'create_time' : orders.sort
  where.entryBillId = entryBillForm?.id ?? 0
  await pageEntryBillSon({ ...where, ...orders, page, limit }).then(data => {
    data_temp = data.list
  })
  return new Promise((resolve) => {
    resolve(data_temp)
  })

};

/* 搜索 */
const entryBillSonReload = () => {
  entryBillSonTableRef?.value?.reload({ page: 1, where: entryBillSonWhere });
};
const entryBillSonReload2 = () => {
  entryBillSonTableRef?.value?.reload();
};

let entryBillSonWhere_timeout = 0
watch(() => entryBillSonWhere, (val) => {
  clearTimeout(entryBillSonWhere_timeout)
  entryBillSonWhere_timeout = setTimeout(() => {
    entryBillSonReload();
  }, TIME_OUT);
},
  { deep: true }
)

/*  重置 */
const entryBillSonReset = () => {
  resetFields();
  entryBillSonReload();
};


// 当前选中数据
const entryBillSonCurrent = ref(null);

// 弹窗是否打开
const entryBillSonVisible_modal = ref(false);

// 是否是修改
const entryBillSonIsUpdate = ref(false);

// 提交状态
const loading = ref(false);

const entryBillSonFormRef = ref(null);

// 表单数据
const { form: entryBillSonForm, resetFields: entryBillSonResetFormFields } = useFormData({
  id: undefined,
  customer: '',
  vessel: '',
  num2: 0,
  litotalweight2: 0,
  actualweight: 0,
  price: 0,
});

// 表单验证规则
const entryBillSonRules = reactive({
  warehousename_val: [{
    required: true, message: '请输入仓库', type: 'string',
  }],
  productname_val: [{
    required: true, message: '请输入产品', type: 'string',
  }],
  specification: [{
    required: true, message: '请输入规格', type: 'string',
  }],
  negative: [{
    required: true, message: '请输入负差',
  }],
  lengths: [{
    required: true, message: '请输入长度',
  }],
  liweight: [{
    required: true, message: '请输入理论质量',
  }],
  num: [{
    required: true, message: '请输入数量',
  }],
  litotalweight: [{
    required: true, message: '请输入总重量',
  }],
  actualweight: [{
    required: true, message: '请输入销售重量',
  }],
  price: [{
    required: true, message: '请输入价格',
  }],
  totalprice: [{
    required: true, message: '请输入总价',
  }],
});



//防止重复刷新
//仓库名称下拉列表
let warehousename_m_timeout = 0
const warehousenameOptions = ref([]);
const warehousename_onSearch = searchText => {
  clearTimeout(warehousename_m_timeout)
  warehousename_m_timeout = setTimeout(() => {
    listWarehouseSel({ name: searchText }).then(msg => {
      warehousenameOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
warehousename_onSearch('')
const warehousename_onSelect = (value2, option2) => {
  // let a = warehousenameOptions.value.find((item)=> {return item.value=value})
  entryBillSonForm.warehousename_val = option2.label
  entryBillSonForm.warehousename = option2.label
  entryBillSonForm.warehousenameId = option2.value
  countBlur()
};
const warehousename_m_change = (value2) => {
  // let a = warehousenameOptions.value.find((item)=> {return item.value=value2})
  // entryBillSonForm.warehousename_val=a.label
  // entryBillSonForm.warehousename=a.label
};
const warehousename_blur = () => {
  entryBillSonForm.warehousename_val = entryBillSonForm.warehousename
};

//产品名称下拉列表
let productname_m_timeout = 0
const productnameOptions = ref([]);
const productname_onSearch = searchText => {
  clearTimeout(productname_m_timeout)
  productname_m_timeout = setTimeout(() => {
    listProductSel({ name: searchText }).then(msg => {
      productnameOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
productname_onSearch('')
const productname_onSelect = (value2, option2) => {
  // let a = productnameOptions.value.find((item)=> {return item.value=value})
  entryBillSonForm.productname_val = option2.name
  entryBillSonForm.productname = option2.name
  entryBillSonForm.productnameId = option2.value
  entryBillSonForm.specification = option2.specification
  entryBillSonForm.liweight = option2.liWeight
  entryBillSonForm.lengths = option2.lengths
  entryBillSonForm.negative = option2.negative
  entryBillSonForm.code = option2.code
  countBlur()
};
const productname_m_change = (value2) => {
  // let a = productnameOptions.value.find((item)=> {return item.value=value2})
  // entryBillSonForm.productname_val=a.label
  // entryBillSonForm.productname=a.label
};
const productname_blur = () => {
  entryBillSonForm.productname_val = entryBillSonForm.productname
};
let pattern = /^-?\d+(\.\d+)?$/ //判断是否为小数 -1.2
//长度 理论质量 数量  计算 总重量 销售重量
const countBlur = () => {
  if (pattern.test(entryBillSonForm.liweight) && pattern.test(entryBillSonForm.num)
    && pattern.test(entryBillSonForm.lengths)) {
    entryBillSonForm.litotalweight = entryBillSonForm.liweight * entryBillSonForm.num * entryBillSonForm.lengths / 1000;
    entryBillSonForm.litotalweight = entryBillSonForm.litotalweight.toFixed(3)
    entryBillSonForm.actualweight = entryBillSonForm.litotalweight
    priceBlur()
    productStorageNums()
  }
}

//总重量 对应改变 销售重量
const litotalweightBlur = () => {
  if (entryBillSonForm.litotalweight != '') {
    entryBillSonForm.actualweight = entryBillSonForm.litotalweight
    priceBlur()
  }
}
//销售重量 和 价格  计算总价totalprice
const priceBlur = () => {
  if (pattern.test(entryBillSonForm.actualweight) && pattern.test(entryBillSonForm.price)) {
    entryBillSonForm.totalprice = entryBillSonForm.actualweight * entryBillSonForm.price
    entryBillSonForm.totalprice = entryBillSonForm.totalprice.toFixed(2)
  }
}
//得到目前的库存
const productStorageNums = () => {
  if (entryBillSonForm.warehousename && entryBillSonForm.productname
    && entryBillSonForm.specification && entryBillSonForm.negative
    && entryBillSonForm.lengths) {
    let productStorageEntity = {
      warehousename: entryBillSonForm.warehousename,
      productname: entryBillSonForm.productname,
      specification: entryBillSonForm.specification,
      lengths: entryBillSonForm.lengths,
      negative: entryBillSonForm.negative,
    }
    productStorageNum(productStorageEntity).then(data => {
      entryBillSonForm.num2 = data.num
      entryBillSonForm.litotalweight2 = data.litotalweight
    }).catch(e => {
      entryBillSonForm.num2 = 0
      entryBillSonForm.litotalweight2 = 0
    })
  }
}

// const calcTotalPriceMain = () => {
//   calcTotalPrice({ entryBillId: entryBillForm.id }).then(data => {
//     entryBillForm.total=data
//   })
// }


/* 打开编辑弹窗 */
const entryBillSonOpenEdit = (record) => {
  if (!record && data_temp.length >= 7) {
    message.error('最多只能添加7条,打印页面显示不下!')
    return false
  }
  if (!entryBillForm.id) {
    message.error('请先保存入库单主表!')
    return false
  }
  entryBillSonResetFormFields();
  entryBillSonFormRef.value?.clearValidate();
  entryBillSonCurrent.value = record ?? {};
  entryBillSonVisible_modal.value = true;
  Object.assign(entryBillSonForm, record ?? {});
  entryBillSonIsUpdate.value = !!record;
  if (!record) {
    entryBillSonForm.negative = 0
    entryBillSonForm.lengths = 1
    entryBillSonForm.num = 0
    entryBillSonForm.price = 0
    if (warehousenameOptions.value && warehousenameOptions.value.length !== 0) {
      let warehousename_temp = warehousenameOptions.value[0]
      entryBillSonForm.warehousename_val = warehousename_temp.label
      entryBillSonForm.warehousename = warehousename_temp.label
      entryBillSonForm.warehousenameId = warehousename_temp.value
    }
  }
  entryBillSonForm.entryBillId = entryBillForm.id
  entryBillSonForm.warehousename_val = entryBillSonForm.warehousename
  entryBillSonForm.productname_val = entryBillSonForm.productname
  productStorageNums()
};

/* 保存编辑 */
const entryBillSonSave = () => {
  if (!entryBillSonFormRef.value) {
    return;
  }
  entryBillSonFormRef.value.validate().then(() => {
    loading.value = true;
    const saveOrUpdate = entryBillSonIsUpdate.value ? updateEntryBillSon : addEntryBillSon;
    saveOrUpdate(entryBillSonForm).then((msg) => {
      getEntryBill(entryBillForm.id).then((data) => {
        entryBillForm.total = data.total
      })
      loading.value = false;
      message.success(msg);
      entryBillSonVisible_modal.value = false;
      entryBillSonReload2();
      setRouteReload({
        reloadHome: false,
        reloadPath: '/store/entryBill'
      });
      setRouteReload({
        reloadHome: false,
        reloadPath: '/store/productStorage'
      });
    }).catch((e) => {
      loading.value = false;
      message.error(e.message);
    });
  }).catch(() => {
  });
};

/* 删除单个 */
const entryBillSonRemove = (record) => {
  const hide = message.loading('请求中..', 0);
  removeEntryBillSon({ id: record.id, entryBillId: record.entryBillId }).then((msg) => {
    getEntryBill(entryBillForm.id).then((data) => {
      entryBillForm.total = data.total
    })
    hide();
    message.success(msg);
    entryBillSonReload2();
    setRouteReload({
      reloadHome: false,
      reloadPath: '/store/entryBill'
    });
    setRouteReload({
      reloadHome: false,
      reloadPath: '/store/productStorage'
    });
  }).catch((e) => {
    hide();
    message.error(e.message);
  });
};


//
const productVisible_modal = ref(false);
//
const productloading = ref(false);
const productRef = ref(null);


const openProduct = () => {
  productVisible_modal.value = !productVisible_modal.value
}
const productSelect = () => {
  productRef.value.selectedProduct()
}
const pSelect_m = (data) => {
  let data1 = data.currentProductTableSelect.value
  productloading.value = false
  productVisible_modal.value = false
  entryBillSonForm.productname_val = data1.name
  entryBillSonForm.productname = data1.name
  entryBillSonForm.productnameId = data1.id
  entryBillSonForm.specification = data1.specification
  entryBillSonForm.liweight = data1.liweight
  entryBillSonForm.lengths = data1.lengths
  entryBillSonForm.negative = data1.negative
  entryBillSonForm.code = data1.code
  countBlur()
}

//-------------son ----------------

</script>
<script>
export default {
  name: 'EntryBilMain_son'
};
</script>

<style lang="less" scoped>
@import "@/assets/css/public.less";

.re {
  background-color: @button-pay;
}

.right {
  display: flex;
  justify-content: end;
}

.m5 {
  margin-left: 15px;
}

.storage :deep(.ant-form-item-label > label) {
  // background-color: @storage_item;
  color: @storage_item;
}
</style>
